<?php

namespace app\common\model\hfztcy;

use app\common\model\BaseModel;
use common\Common;
use think\Db;
use think\Exception;

//公共函数

/**
 * 异步支付
 * @name LibNotifyPay.php
 * @package hfztcy
 * @category model
 * @link http://www.chanekeji.com
 * @author rxy
 * @version 1.0
 * @copyright CHANGE INC
 * @since 2022-06-17
 */
class LibNotifyPay extends BaseModel
{
    public $rawOrderNum;
    public $total_fee;
    public $transaction_id;

    public function __construct($rawOrderNum,$total_fee,$transaction_id)
    {
        $this->rawOrderNum = $rawOrderNum;
        $this->total_fee = $total_fee;
        $this->transaction_id = $transaction_id;
        parent::__construct();
    }

    /**
     * Info: 一元看视频
     * Date: 2022/11/15 18:50
     */
    public function orderByOneYuanSeeVideo ()
    {
        Db::startTrans();
        try {
            $sql = <<< SQL
SELECT a.*,
       b.state,b.direct_user_id,b.private_red_mother_id,b.store_user_id,b.shi_admin_id,b.xian_admin_id,
       b.zt_commission_money,b.zs_commission_money,b.md_commission_money,b.shi_commission_money,b.xian_commission_money,b.pt_commission_money
FROM `hfztcy_order` AS a 
    INNER JOIN `hfztcy_order_one_yuan` AS b 
        ON `a`.`id` = `b`.`order_id` 
WHERE `a`.`code` = '{$this->rawOrderNum}'
SQL;
            $result = Db::query($sql);
            if (empty($result)) {
                return Common::errorArray(1,'订单号不存在',false);
            }
            $orderInfo = $result[0];
            $arr[]['order_sql1'] = $sql;

            // 判断订单状态
            if ($orderInfo['state'] > 1 && !empty($orderInfo['transaction_id'])) {
                return Common::errorArray(1,'订单已支付',false);
            }

            // 更新订单支付金额、支付时间和流水号
            $add_time = date('Y-m-d H:i:s',time());
            $updateOrderSql = <<< SQL
UPDATE hfztcy_order 
SET pay_amount='{$this->total_fee}',pay_time = '{$add_time}',transaction_id='{$this->transaction_id}' 
WHERE `code` = '{$this->rawOrderNum}'
SQL;
            Db::execute($updateOrderSql);
            $arr[]['order_sql2'] = $updateOrderSql;
            // 更新子订单状态
            $sql = <<< SQL
UPDATE hfztcy_order_one_yuan 
SET state=1 
WHERE `order_id` = '{$orderInfo['id']}'
SQL;
            Db::execute($sql);
            $arr[]['order_sql3'] = $sql;
            // 完成分销
            $result = (new LibDistribute($orderInfo))->setOrderType(0)->updateUserBalance();
            Db::commit();
            return Common::errorArray(0,'success',array_merge($arr,$result));
        } catch (Exception $exception) {
            Db::rollback();
            return Common::errorArray(1,$exception->getMessage(),false);
        }
    }

    /**
     * Info: vip套餐支付
     * Date: 2022/11/15 18:55
     */
    public function orderByVip ()
    {
        Db::startTrans();
        try {
            $sql = <<< SQL
SELECT a.id,a.code,a.type,a.user_id,
       b.vip_id,b.vip_info,b.amount,b.state,
       b.shi_admin_id,b.xian_admin_id,b.shi_commission_money,b.xian_commission_money,b.pt_commission_money
FROM `hfztcy_order` AS a 
    INNER JOIN `hfztcy_order_vip` AS b 
        ON `a`.`id` = `b`.`order_id` 
WHERE `a`.`code` = '{$this->rawOrderNum}'
SQL;
            $result = Db::query($sql);
            // 订单是否存在
            if (empty($result)) {
                return Common::errorArray(1,'订单号不存在',false);
            }

            $orderInfo = $result[0];
            $arr[]['order_sql1'] = $sql;

            // 判断订单状态
            if ($orderInfo['state'] > 1 && !empty($orderInfo['transaction_id'])) {
                return Common::errorArray(1,'订单已支付',false);
            }

            // 套餐信息
            $vipInfo = json_decode($orderInfo['vip_info'],true);
            $dayTimestamp =  $vipInfo['day'] * 24 * 60 * 60;

            // 更新订单支付金额、支付时间和流水号
            $add_time = date('Y-m-d H:i:s',time());
            $updateOrderSql = <<< SQL
UPDATE hfztcy_order 
SET pay_amount='{$this->total_fee}',pay_time = '{$add_time}',transaction_id='{$this->transaction_id}' 
WHERE `code` = '{$this->rawOrderNum}'
SQL;
            Db::execute($updateOrderSql);
            $arr[]['order_sql2'] = $updateOrderSql;
            // 更新子订单状态
            $sql = <<< SQL
UPDATE hfztcy_order_vip 
SET state=1 
WHERE `order_id` = '{$orderInfo['id']}'
SQL;
            Db::execute($sql);
            $arr[]['order_sql3'] = $sql;
            // 更新用户开通VIP时间
            $vip_open_time = time() + $dayTimestamp;
            $sql = <<< SQL
SELECT a.*  
FROM `hfztcy_user` AS a 
WHERE `a`.`user_id` = '{$orderInfo['user_id']}'
SQL;
            $userInfo = Db::query($sql);
            if (!empty($userInfo['vip_open_time'])) {
                $vip_open_time = $userInfo['vip_open_time'] + $dayTimestamp;
            }
            $sql = <<< SQL
UPDATE hfztcy_user 
SET is_vip={$orderInfo['id']},vip_open_time={$vip_open_time},state=2 
WHERE `user_id` = '{$orderInfo['user_id']}'
SQL;
            Db::execute($sql);
            $arr[]['order_sql4'] = $sql;
            // 更新用户身份
            $sql = <<< SQL
UPDATE base_user 
SET identity=2 
WHERE `id` = '{$orderInfo['user_id']}'
SQL;
            Db::execute($sql);
            $arr[]['order_sql5'] = $sql;
            // 完成分销
            $result = (new LibDistribute($orderInfo))->setOrderType(1)->updateUserBalance();
            Db::commit();
            return Common::errorArray(0,'success',array_merge($arr,$result));
        } catch (Exception $exception) {
            Db::rollback();
            return Common::errorArray(1,$exception->getMessage(),false);
        }
    }

    /**
     * Info: 视频认证 佣金发放是在后台审核视频通过后一起结算
     * Date: 2022/11/15 18:56
     */
    public function orderByVipAuth ()
    {
        Db::startTrans();
        try {
            // 订单信息
            $sql = <<< SQL
SELECT a.id,a.code,a.type,a.user_id,
       b.amount,b.state,b.direct_user_id,b.indirect_user_id,b.store_user_id,b.shi_admin_id,b.xian_admin_id,b.kf_admin_id,b.px_admin_id,
       b.zt_commission_money,b.jt_commission_money,b.md_commission_money,b.shi_commission_money,b.xian_commission_money,b.kf_commission_money,b.px_commission_money,b.pt_commission_money,
       b.package_id,b.package_info
FROM `hfztcy_order` AS a 
    INNER JOIN `hfztcy_order_vip_auth` AS b 
        ON `a`.`id` = `b`.`order_id` 
WHERE `a`.`code` = '{$this->rawOrderNum}'
SQL;
            $result = Db::query($sql);
            // 订单是否存在
            if (empty($result)) {
                return Common::errorArray(1,'订单号不存在',false);
            }

            $orderInfo = $result[0];
            $arr[]['order_sql1'] = $sql;

            // 判断订单状态
            if ($orderInfo['state'] > 1 && !empty($orderInfo['transaction_id'])) {
                return Common::errorArray(1,'订单已支付',false);
            }

            // 更新订单支付金额、支付时间和流水号
            $add_time = date('Y-m-d H:i:s',time());
            $updateOrderSql = <<< SQL
UPDATE hfztcy_order 
SET pay_amount='{$this->total_fee}',pay_time = '{$add_time}',transaction_id='{$this->transaction_id}' 
WHERE `code` = '{$this->rawOrderNum}'
SQL;
            Db::execute($updateOrderSql);
            $arr[]['order_sql2'] = $updateOrderSql;
            // 更新子订单状态
            $sql = <<< SQL
UPDATE hfztcy_order_vip_auth 
SET state=1 
WHERE `order_id` = '{$orderInfo['id']}'
SQL;
            Db::execute($sql);
            $arr[]['order_sql3'] = $sql;
            $result = [];
            Db::commit();
            return Common::errorArray(0,'success',array_merge($arr,$result));
        } catch (Exception $exception) {
            Db::rollback();
            return Common::errorArray(1,$exception->getMessage(),false);
        }
    }

    /**
     * Info: 红娘认证
     * Date: 2022/11/15 18:58
     */
    public function orderByRedMotherAuth ()
    {
        Db::startTrans();
        try {
            // 订单信息
            $sql = <<< SQL
SELECT a.id,a.code,a.type,a.user_id,
       b.amount,b.state,b.direct_user_id,b.indirect_user_id,b.shi_admin_id,b.xian_admin_id,b.kf_admin_id,b.px_admin_id,
       b.zt_commission_money,b.jt_commission_money,b.shi_commission_money,b.xian_commission_money,b.kf_commission_money,b.px_commission_money,b.pt_commission_money
FROM `hfztcy_order` AS a 
    INNER JOIN `hfztcy_order_red_mother` AS b 
        ON `a`.`id` = `b`.`order_id` 
WHERE `a`.`code` = '{$this->rawOrderNum}'
SQL;
            $result = Db::query($sql);
            // 订单是否存在
            if (empty($result)) {
                return Common::errorArray(1,'订单号不存在',false);
            }

            $orderInfo = $result[0];
            $arr[]['order_sql1'] = $sql;

            // 判断订单状态
            if ($orderInfo['state'] > 1 && !empty($orderInfo['transaction_id'])) {
                return Common::errorArray(1,'订单已支付',false);
            }

            // 更新订单支付金额、支付时间和流水号
            $add_time = date('Y-m-d H:i:s',time());
            $updateOrderSql = <<< SQL
UPDATE hfztcy_order 
SET pay_amount='{$this->total_fee}',pay_time = '{$add_time}',transaction_id='{$this->transaction_id}' 
WHERE `code` = '{$this->rawOrderNum}'
SQL;
            Db::execute($updateOrderSql);
            $arr[]['order_sql2'] = $updateOrderSql;
            // 更新子订单状态
            $sql = <<< SQL
UPDATE hfztcy_order_red_mother 
SET state=1 
WHERE `order_id` = '{$orderInfo['id']}'
SQL;
            Db::execute($sql);
            $arr[]['order_sql3'] = $sql;
            // 变更用户身份
            $user_id = (int)$orderInfo['user_id'];
            $sql = <<< SQL
SELECT identity FROM `base_user` WHERE `id` = {$user_id}
SQL;
            $userRes = Db::query($sql);
            $identity = [];
            if ($userRes) {
                $identity = explode(',',$userRes[0]['identity']);
            }
            $identity = array_map('intval',$identity);
            array_push($identity,3);
            //排除游客，普通会员，增加红娘身份
            $identity = array_map(function ($val) use ($identity) {
                if ($val <= 1) {
                    unset($identity[$val]);
                } else {
                    return $val;
                }
            },$identity);
            $identity = array_filter($identity);
            $identity = array_unique($identity);
            if ($identity) {
                $identityStr = implode(',',$identity);
                $sql = <<< SQL
UPDATE base_user 
SET identity='{$identityStr}' 
WHERE `id` = '{$user_id}'
SQL;
                Db::execute($sql);
                $arr[]['order_sql4'] = $sql;

                $sql = <<< SQL
UPDATE hfztcy_user 
SET state='{$identityStr}' 
WHERE `user_id` = '{$user_id}'
SQL;
                Db::execute($sql);
                $arr[]['order_sql5'] = $sql;
            }
            // 完成分销
            $result = (new LibDistribute($orderInfo))->setOrderType(2)->updateUserBalance();
            Db::commit();
            return Common::errorArray(0,'success',array_merge($arr,$result));
        } catch (Exception $exception) {
            Db::rollback();
            return Common::errorArray(1,$exception->getMessage(),false);
        }
    }

    /**
     * Info: 管理员点击认证订单完成按钮，执行分销操作。
     * Date: 2022/11/17 13:48
     */
    public function adminClickOrderCompleteBtnByVipAuth ()
    {
        // 订单信息
        $sql = <<< SQL
SELECT a.id,a.code,a.type,a.user_id,a.store_id,
       b.amount,b.state,b.direct_user_id,b.indirect_user_id,b.store_user_id,b.shi_admin_id,b.xian_admin_id,b.kf_admin_id,b.px_admin_id,
       b.zt_commission_money,b.jt_commission_money,b.md_commission_money,b.shi_commission_money,b.xian_commission_money,b.kf_commission_money,b.px_commission_money,b.pt_commission_money,
       b.package_id,b.package_info,b.is_offline
FROM `hfztcy_order` AS a 
    INNER JOIN `hfztcy_order_vip_auth` AS b 
        ON `a`.`id` = `b`.`order_id` 
WHERE `a`.`code` = '{$this->rawOrderNum}'
SQL;
        $result = Db::query($sql);
        // 订单是否存在
        if (empty($result)) return Common::errorArray(1,'订单号不存在',false);
        $orderInfo = $result[0];
        // 门店信息
        if ($orderInfo['store_id']) {
            $storeModel = new LibStore();
            $findStoreRes = $storeModel->findStore(['id' => $orderInfo['store_id']]);
            $orderInfo['store'] = $findStoreRes['data'];
        }
        // 套餐信息
        if ($orderInfo['package_info']) {
            $orderInfo['package_info'] = json_decode($orderInfo['package_info'],true);
        }
        // 判断订单状态
        if ($orderInfo['state'] > 1 && !empty($orderInfo['transaction_id'])) return Common::errorArray(1,'订单已支付',false);
        $result = (new LibDistribute($orderInfo))->setOrderType(3)->updateUserBalance();
        return Common::errorArray(0,'success',$result);
    }
}

?>